package com.jcompressor.faces.component.renderer;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;

import com.jcompressor.faces.component.UIResource;
import com.jcompressor.type.ResourceType;

public class UIResourceRenderer extends Renderer {
	
	@Override
	public void encodeBegin(final FacesContext facesContext, final UIComponent component) throws IOException {
		super.encodeBegin(facesContext, component);
		
		if (!component.isRendered()) {
			return;
		}
		
		final UIResource resource = (UIResource)component;
		final ResponseWriter writer = facesContext.getResponseWriter();
		
		if (StringUtils.equals(resource.getAttributes().get("type").toString(), ResourceType.SCRIPT.getContentType())) {
			writer.startElement("script", null);
			writer.writeAttribute("type", ResourceType.SCRIPT.getContentType(), null);
			writer.writeAttribute("src", this.buildRelativePath(facesContext, resource.getAttributes().get("path").toString()), null);
			writer.endElement("script");
		}
		else if (StringUtils.equals(resource.getAttributes().get("type").toString(), ResourceType.STYLE.getContentType())) {
			writer.startElement("link", null);
			writer.writeAttribute("type", ResourceType.STYLE.getContentType(), null);
			writer.writeAttribute("rel", "stylesheet", null);
			writer.writeAttribute("href", this.buildRelativePath(facesContext, resource.getAttributes().get("path").toString()), null);
			writer.writeAttribute("class", "component", null);
			writer.endElement("link");
		}
	}
	
	@Override
	public void encodeEnd(final FacesContext facesContext, final UIComponent component) throws IOException {
		final UIResource resource = (UIResource)component;
		super.encodeEnd(facesContext, resource);
		
		if (!component.isRendered()) {
			return;
		}
	}
	
	private String buildRelativePath(final FacesContext facesContext, final String path) {
		final HttpServletRequest request = (HttpServletRequest)facesContext.getExternalContext().getRequest();
		final StrBuilder builder = new StrBuilder(request.getContextPath());
		builder.append(path);
		return builder.toString();
	}
	
}